package br.com.consultsystems.persistencia.impl.financeiro;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import br.com.consultsystems.dominio.financeiro.Banco;
import br.com.consultsystems.persistencia.spec.AbstractAdministradoraRepository;
import br.com.consultsystems.persistencia.spec.financeiro.BancoPersistencia;

@Stateless(name = "bancoPersistencia")
public class BancoPersistenciaImpl extends
		AbstractAdministradoraRepository<Banco> implements
		BancoPersistencia {

	protected BancoPersistenciaImpl() {
		super(Banco.class);
	}

	@Override
	public List<Banco> retrieveAll() {
		return retrieveByCriteria(null);
	}

	@Override
	public List<Banco> retrieveByFilter(String nome) throws Exception {

		final EntityManager em = getEntityManager();
		final CriteriaBuilder criteriaBuilder = createCriteriaBuilder();
		final CriteriaQuery<Banco> criteriaQuery = createCriteriaQuery(criteriaBuilder);
		final Root<Banco> root = createRoot(criteriaQuery);
		
		/* Repository -> Apenas pesquias as informações no banco de dados
		 * Filtro por codigo */
		final Path<String> pathBanco = root.get("nome");
		final Predicate predicateBanco = criteriaBuilder.like(pathBanco, "%"+nome+"%");
		criteriaQuery.where(predicateBanco);
		criteriaQuery.orderBy(criteriaBuilder.asc(pathBanco));
		
		final TypedQuery<Banco> typedQuery = em.createQuery(criteriaQuery);
		
		return typedQuery.getResultList();
	}

}
